import {
  Button,
  Card,
  Col,
  Input,
  message,
  Pagination,
  type PaginationProps,
  Popconfirm,
  Row,
  Table,
  type TableProps,
  Tag,
} from 'antd'
import './index.scss'
import type { DataType, QueryForm } from './interface'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import type { Key, ChangeEvent } from 'react'
import { deleteBatchById, deleteById, getUserList } from '../../api/users.ts'
import UserForm from './UserForm.tsx'
import { useDispatch } from 'react-redux'
import { setUserData } from '../../store/user/userSlice.ts'

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection']

export default function Users() {
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<Array<DataType>>([])
  const [total, setTotal] = useState(1)
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [pageNumber, setPageNumber] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [userFormTitle, setUserFormTitle] = useState('')
  const [userFormShow, setUserFormShow] = useState<boolean>(false)
  const dispatch = useDispatch()

  // 缓存组件，防止每次渲染都重新创建组件，导致userForm组件重复渲染
  const MyUserForm = memo(UserForm)

  const [queryForm, setQueryForm] = useState<QueryForm>({
    companyName: '',
    contact: '',
    phone: '',
  })

  useEffect(() => {
    loadData()
  }, [pageNumber, pageSize])

  const disabled = useMemo(() => {
    return selectedRowKeys.length <= 0
  }, [selectedRowKeys])

  const columns = [
    {
      title: 'No',
      key: 'index',
      render: (_value: any, _record: any, index: number) => index + 1,
    },
    {
      title: '客户名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '经营状态',
      key: 'status',
      dataIndex: 'status',
      render: (status: number) => {
        if (status == 1) {
          return <Tag color="green">营业中</Tag>
        } else if (status == 2) {
          return <Tag color="#f50">暂停营业</Tag>
        } else {
          return <Tag color="red">已关闭</Tag>
        }
      },
    },
    {
      title: '联系电话',
      key: 'tel',
      dataIndex: 'tel',
    },
    {
      title: '所属行业',
      key: 'business',
      dataIndex: 'business',
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
    },
    {
      title: '统一信用代码',
      key: 'creditCode',
      dataIndex: 'creditCode',
    },
    {
      title: '工商注册号',
      key: 'industryNum',
      dataIndex: 'industryNum',
    },
    {
      title: '组织结构代码',
      key: 'organizationCode',
      dataIndex: 'organizationCode',
    },
    {
      title: '法人名',
      key: 'legalPerson',
      dataIndex: 'legalPerson',
    },
    {
      title: '操作',
      key: 'legalPerson',
      render: (_value: any, record: DataType) => (
        <div className="btn-group">
          <Row gutter={15} wrap={false}>
            <Col span={12}>
              <Button type="primary" size="small" onClick={() => handleEdit(record)}>
                编辑
              </Button>
            </Col>
            <Col span={12}>
              <Popconfirm
                title="删除确认"
                description="确定要删除吗？"
                okText="确认"
                cancelText="取消"
                onConfirm={() => handleDeleteSingle(record.id)}
              >
                <Button type="primary" danger size="small">
                  删除
                </Button>
              </Popconfirm>
            </Col>
          </Row>
        </div>
      ),
    },
  ]

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    // 解构出输入框的名字和值
    const { name, value } = e.target
    // 拿到前值，强制更新queryForm。放置setState异步更新不及时，后端获取不到最新的值
    setQueryForm((prevState: QueryForm) => ({
      ...prevState,
      [name]: value,
    }))
  }

  const loadData = async () => {
    setLoading(true)
    const {
      data: { list, total },
    } = await getUserList({ ...queryForm, pageNumber, pageSize })
    setDataSource(list)
    setTotal(total)
    setLoading(false)
  }

  const onSelectChange = (newSelectedRowKeys: Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys)
  }

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  const handlePageChange: PaginationProps['onChange'] = (pageNo: number, pageSize: number) => {
    setPageNumber(pageNo)
    setPageSize(pageSize)
  }

  const handleQuery = () => {
    loadData()
  }

  function handleReset() {
    setQueryForm({
      companyName: '',
      contact: '',
      phone: '',
    })
    setPageNumber(1)
    setPageSize(10)
    loadData()
  }

  const handleDeleteSingle = async (id: number) => {
    deleteById(id).then(() => {
      message.success('删除成功')
      loadData()
    })
  }

  const handleBatchDelete = async () => {
    await deleteBatchById([...selectedRowKeys]).then(() => {
      message.success('批量删除成功')
      loadData()
      setSelectedRowKeys([])
    })
  }

  const handleEdit = (record: DataType) => {
    setUserFormTitle('编辑企业')
    setUserFormShow(true)
    dispatch(setUserData(record))
  }

  const handleAdd = () => {
    setUserFormTitle('新增企业')
    setUserFormShow(true)
  }

  // 使用usecallback缓存函数，防止每次渲染都重新创建函数，导致userForm组件重复渲染
  const handleCloseUserForm = useCallback(() => {
    setUserFormShow(false)
  }, [])

  return (
    <div className="user">
      <MyUserForm
        show={userFormShow}
        title={userFormTitle}
        loadData={loadData}
        handleCloseUserForm={handleCloseUserForm}
      />
      <Card className="search">
        <Row gutter={16}>
          <Col span={7}>
            <p>企业名称:</p>
            <Input value={queryForm.companyName} onChange={handleChange} name="companyName" />
          </Col>
          <Col span={7}>
            <p>联系人:</p>
            <Input value={queryForm.contact} onChange={handleChange} name="contact" />
          </Col>
          <Col span={7}>
            <p>联系电话:</p>
            <Input value={queryForm.phone} onChange={handleChange} name="phone" />
          </Col>
          <Col span={3}>
            <Button type="primary" onClick={handleQuery}>
              查询
            </Button>
            <Button type="default" className="ml" onClick={handleReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Card>
      <Card className="tr mt">
        <Button type="primary" onClick={handleAdd}>
          新增企业
        </Button>
        <Button type="primary" danger className="ml" onClick={handleBatchDelete} disabled={disabled}>
          批量删除
        </Button>
      </Card>
      <Card>
        <Table<DataType>
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          rowKey={(record) => record.id}
          rowSelection={rowSelection}
          pagination={false}
        />
        <Pagination
          className="fr"
          showQuickJumper
          defaultCurrent={1}
          total={total}
          onChange={handlePageChange}
          current={pageNumber}
          pageSize={pageSize}
        />
      </Card>
    </div>
  )
}
